#define  _CRT_SECURE_NO_WARNINGS 1
#include"SList.h"

SLTNode* BuySLnode(SLTDataType x) {
	SLTNode* newnode = (SLTNode*)malloc(sizeof(SLTNode));
	if (newnode==NULL) {
		perror("BuySLnode");
		exit(-1);
	}
	newnode->data = x;
	newnode->next = NULL;
	return newnode;
}
SLTNode* CreateSList(int n) {
	SLTNode* phead = NULL, * ptail = NULL;
	int x = 0;
	for (int i = 0; i < n;i++) {
		SLTNode* newnode = BuySLnode(i);
		if (phead==NULL) {
			ptail = phead = newnode;
		}
		else {
			ptail->next = newnode;
			ptail = newnode;
		}
	}
	return phead;
}


void SLTPrint(SLTNode* phead) {
	SLTNode* cur = phead;
	while (cur !=NULL) {
		printf("%d->",cur->data);
		//printf("[%d|%p]->", cur->data,cur->next);

		cur = cur->next;
	}
	printf("NULL\n");
}

void SLTPushBack(SLTNode** pphead, SLTDataType x) {
	SLTNode* newnode = BuySLnode(x);
	if (*pphead==NULL) {
		*pphead = newnode;
	}
	else {
		SLTNode* tail = *pphead;
		while (tail->next)
		{
			tail = tail->next;
		}
		tail->next = newnode;
	}
}

void SLTPopBack(SLTNode** pphead) {
	assert(*pphead);
	if ((*pphead)->next==NULL) {
		free(*pphead);
		*pphead = NULL;
	}
	else {
		//SLTNode* tail = *pphead;
		//while (tail->next->next) {
		//	tail = tail->next;
		//}
		//free(tail->next);
		//tail->next = NULL;


		SLTNode* prev = NULL;
		SLTNode* tail = *pphead;
		while (tail->next)
		{
		prev = tail;
		tail = tail->next;
		}

		free(tail);
		prev->next = NULL;
	}
}

void SLTPushFront(SLTNode** pphead, SLTDataType x) {
	SLTNode* newnode = BuySLnode(x);
	newnode->next = *pphead;
	*pphead = newnode;
}
void SLTPopFront(SLTNode** pphead) {
	assert(*pphead);
	SLTNode* next= (*pphead)->next;
	free(*pphead);
	*pphead = next;
}

SLTNode* SLTFind(SLTNode* phead, SLTDataType x){
	SLTNode* cur=phead;
	while (cur) {
		if (cur->data==x) {
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

void SLTInsertAfter(SLTNode* pos, SLTDataType x) {
	assert(pos);
	SLTNode* newnode = BuySLnode(x);
	newnode->next = pos->next;
	pos->next=newnode;
}

void SLTInsert(SLTNode** pphead, SLTNode* pos, SLTDataType x) {
	assert(pos);
	if (*pphead==pos) {
		SLTPushFront(pphead,x);
	}
	else {
		SLTNode* prev = *pphead;
		while (prev->next !=pos) {
			prev = prev->next;
		}
		SLTNode* newnode = BuySLnode(x);
		newnode->next = prev->next;
		prev->next = newnode;
	}
}

void SLTEraseAfter(SLTNode* pos) {
	assert(pos);
	if (pos->next==NULL) {
		return;
	}
	else
	{
		SLTNode* nextnode = pos->next;
		pos->next = nextnode->next;
		free(nextnode);
	}
}


void SLTErase(SLTNode** pphead, SLTNode* pos) {
	assert(pos);
	assert(pphead);
	if (pos==*pphead) {
		SLTPopFront(pphead);
	}
	else {
		SLTNode* prev = *pphead;
		while (prev->next !=pos) {
			prev = prev->next;
		}
		prev->next = pos->next;
		free(pos);
	}
}

void SLTDestroy(SLTNode** pphead) {
	SLTNode* cur = *pphead;
	while (cur) {
		SLTNode* next = cur->next;
		free(cur);
		cur = next;
	}
	*pphead = NULL;
}